<template>
	<mg-form>
		<view class="mh100 bf">
			<view class="paytop f-c-c">
				<image class="payimg" src="/static/pay/payok.png"></image>
				<!-- <view v-if="payObj.orderType==1" class="f26 c9 mt30">支付剩余时间<text class="ml10" v-if="stime">{{stime[2]}}:{{stime[3]}}</text></view> -->
				<view class="paymoeny wei"><text class="f30">{{sl}}</text><text class="f60 ml5">{{pmoney}}</text></view>
				<mg-cell hc='1' @tab="go({t:1,url:'/yb_o2o/order/order-dl?id='+info.id})" v-if="payObj.orderType==1&&info" cname="p13"
				 last='1' :btt='`${info.storeName} 订单详情`' bttc="f26 c9" arrow="1"></mg-cell>
				<view v-if="payObj.orderType" class="p13 f26 c9">{{payObj.info.type}}</view>
			</view>
			<form @submit="formSubmit">
				<view class="">
					<radio-group name='radiogroup'>
						<label class="weui-cell weui-check__label right30" v-for='(v,i) in payArr' :key='i'>
							<view class="weui-cell__hd f-y-c">
								<image class='hdimg' mode='aspectFit' :src='v.img'></image>
							</view>
							<view class="weui-cell__bd">
								<view class="f34 wei">{{v.name}}</view>
								<view class='yezf' v-if="v.value=='ye'">
									可用余额
									<text :style='{color:tColor}'>{{sl+user.balance}}</text>
								</view>
							</view>
							<view class="weui-cell__ft weui-cell__ft_in-radio">
								<radio :value="v.value" color="#07C160" :checked="v.checked" />
							</view>
						</label>
					</radio-group>
				</view>
				<view v-if="payArr.length" class="foot-btnc">
					<button :disabled="loading" :loading="loading" form-type="submit" class="foot-btn b-s-2 bs0 f30 wei" :style="{background:'#07C160'}">确认支付</button>
				</view>
			</form>
		</view>
	</mg-form>
</template>

<script>
	import {
		mapActions,
		mapState,
		mapGetters
	} from "vuex";
	import mgPopup from '@/components/common/popup.vue'
	import mgModal from '@/components/common/modal.vue'
	import MgCell from '@/components/common/mg-cell.vue'
	import utils from '@/common/utils.js'
	import {
		utilMixins
	} from "@/common/util-mixins.js"
	import {
		chooseWXPay
	} from "@/common/wechat-util"
	export default {
		name: 'mg-pay',
		components: {
			mgPopup,
			mgModal,
		},
		data() {
			return {
				loading: false,
				payObj: {},
				payArr: [],
				showCoupon: false,
				stime: '',
				info: null, //订单详情
			}
		},
		async onLoad(options) {
			this.util.setNT('收银台')
			uni.getProvider({
				service: 'payment',
				success: (res) => {
					if (res.provider.indexOf('wxpay')) {
						this.provider = 'wxpay'
					} else if (res.provider.indexOf('alipay')) {
						this.provider = 'alipay'
					} else if (res.provider.indexOf('baidu')) {
						this.provider = 'baidu'
					} else if (res.provider.indexOf('toutiao')) {
						this.provider = 'toutiao'
					}
					// console.log(res.provider)
				}
			});
			this.payObj = JSON.parse(decodeURIComponent(options.payObj))
			this.refreshUser({
				get: 1,
			}, true)
			this.getConfig({
				key: 'payConfig',
				api: 'config',
				params: {
					ident: 'payConfig'
				}
			}).then(res => {
				this.getPayArr()
			})
			// if (this.payObj.orderType == 1) { //1下单3充值
			// 	let {
			// 		data
			// 	} = await this.util.request({
			// 		'url': this.api.OrderInfo,
			// 		mask: 1,
			// 		data: {
			// 			orderId: this.payObj.orderId
			// 		},
			// 	})
			// 	if (data) {
			// 		this.info = data
			// 		if (data.state == 1) {
			// 			this.djs(data.createdAt)
			// 		}
			// 	}
			// }
			uni.setStorageSync('payPage', true)
			uni.setStorageSync('payedCoupon', false)
			// console.log(options, this.payObj)
		},
		onUnload() {
			setTimeout(() => {
				uni.removeStorageSync('payPage');
				this.dsq && clearInterval(this.dsq)
				//console.log('移除payPage')
			}, 1000)
		},
		mixins: [utilMixins],
		computed: {
			...mapState({
				payConfig: state => state.config.payConfig,
			}),
			pmoney() {
				return Number(this.payObj.info && this.payObj.info.money || 0).toFixed(2)
			},
		},
		methods: {
			...mapActions(['getConfig']),
			getPayArr() {
				//可选支付类型
				let payArr = []
				if (this.payConfig.payOpen == 1 || this.payObj.orderType == 3) {
					if (this.api.platform == 'mini' || this.api.platform == 'weChat') {
						payArr.push({
							name: '微信支付',
							value: 'wx',
							img: '/static/pay/wxzf.png',
						})
					} else if (this.api.platform == 'ali') {
						payArr.push({
							name: '支付宝支付',
							value: 'zfb',
							img: '/static/pay/zfbzf.png',
						})
					} else if (this.api.platform == 'baidu') {
						payArr.push({
							name: '百度支付',
							value: 'baidu',
							img: '/static/pay/bdzf.png',
						})
					} else if (this.api.platform == 'toutiao') {
						payArr.push({
							name: '头条支付',
							value: 'baidu',
							img: '/static/pay/ttzf.png',
						})
					}
				}
				if (this.payConfig.balancePayOpen == 1) {
					switch (+this.payObj.orderType) {
						case 3:
							break;
						default:
							payArr.push({
								name: '余额支付',
								value: 'ye',
								img: '/static/pay/yezf.png'
							})
							break;
					}
				}
				payArr[0].checked = true
				this.payArr = payArr
			},
			djs(time) {
				let now = this.dateToTime(),
					time2 = +time + 900
				if (time2 > now) {
					this.stime = utils.countDownTime(time2 - now)
					this.dsq = setInterval(async () => {
						time2 -= 1
						if (time2 == now) {
							clearInterval(this.dsq)
							this.go({
								t: 4
							})
						}
						this.stime = utils.countDownTime(time2 - now)
					}, 1000)
				}
			},
			setzfcg() {
				uni.setStorageSync('payedCoupon', {
					orderId: this.payObj.orderId,
					paymoney: this.pmoney,
				})
			},
			async formSubmit(e) {
				let payObj = utils.deepCopy(this.payObj)
				// console.log(e.detail.value, payObj)
				if (e.detail.value.radiogroup == 'ye') {
					payObj.payType = 1
					if (+this.pmoney > +this.user.balance) {
						return this.util.message('您的余额不足支付', 3)
					}
				}
				// return
				this.loading = true
				// this.util.showLoading()
				// let orderRes = await this.util.request({
				// 	'url': this.api[payobj.api],
				// 	method: 'POST',
				// 	data: payobj.params,
				// })
				// console.log('formSubmit orderRes', orderRes)
				//下单订阅消息
				// // #ifdef MP-WEIXIN
				// if (this.payObj.orderType == 1 && this.info.deliveryMode > 2) {
				// 	await this.requestSM('delivery')
				// }
				// // #endif
				let payres = await this.util.request({
					'url': this.api.pay,
					method: 'POST',
					mask: 1,
					data: payObj,
				})
				if (payres) {
					if (e.detail.value.radiogroup != 'ye') {
						// #ifndef  H5
						uni.requestPayment({
							provider: this.provider,
							// #ifdef MP-WEIXIN
							timeStamp: payres.data.timeStamp,
							nonceStr: payres.data.nonceStr,
							package: payres.data.package,
							signType: payres.data.signType,
							paySign: payres.data.paySign,
							// #endif
							// #ifdef MP-ALIPAY
							orderInfo: payres.data.alipay_trade_create_response.trade_no,
							// #endif
							// #ifdef MP-BAIDU
							orderInfo: {
								"dealId": payres.data.dealId,
								"appKey": payres.data.appKey,
								"totalAmount": payres.data.totalAmount,
								"tpOrderId": payres.data.tpOrderId,
								"dealTitle": payObj.info.type,
								"signFieldsRange": "1",
								"rsaSign": payres.data.sign,
								"bizInfo": ''
							},
							// #endif
							// #ifdef MP-TOUTIAO
							orderInfo: {
								"app_id": payres.data.app_id,
								"method": 'tp.trade.confirm',
								"sign": payres.data.sign,
								"sign_type": payres.data.sign_type,
								"timestamp": payres.data.timestamp + '',
								"trade_no": payres.data.trade_no,
								"merchant_id": payres.data.biz_content.merchant_id,
								"uid": payres.data.biz_content.uid,
								"total_amount": payres.data.biz_content.total_amount,
								pay_channel: 'ALIPAY_NO_SIGN',
								pay_type: 'ALIPAY_APP',
								risk_info: payres.data.biz_content.risk_info,
								"params": JSON.stringify({
									url: payres.data.aliUrl
								}),
							},
							// #endif
							// #ifdef MP-WEIXIN
							success: (res) => {
								this.util.message('支付成功', 1)
								this.setzfcg()
								if (payObj.info.go.t == 4) {
									let lastPage = this.util.getPage()
									lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
									//console.log(lastPage)
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
								// console.log('success:' + JSON.stringify(res));
							},
							fail: (err) => {
								this.util.message('取消支付', 2)
								if (payObj.info.cancel) {
									return this.loading = false;
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
								console.log('fail:' + JSON.stringify(err));
							},
							// #endif
							// #ifdef MP-ALIPAY
							success: (res) => {
								if (res.resultCode == 9000) {
									this.util.message('支付成功', 1)
									if (payObj.info.go.t == 4) {
										let lastPage = this.util.getPage()
										lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
										//console.log(lastPage)
									}
									setTimeout(() => {
										this.go(payObj.info.go)
									}, 1000)
								} else if (res.resultCode == 6001) { //取消支付
									this.util.message('取消支付', 2)
									if (payObj.info.cancel) {
										return this.loading = false;
									}
									setTimeout(() => {
										this.go(payObj.info.go)
									}, 1000)
								} else {
									uni.showModal({
										title: '提示',
										content: JSON.stringify(res),
									});
								}
								console.log('success:' + JSON.stringify(res));
							},
							// #endif
							// #ifdef MP-BAIDU
							success: (res) => {
								this.util.message('支付成功', 1)
								setTimeout(() => {
									this.util.message('请耐心等待，页面即将跳转', 3, 2000)
								}, 1000)
								if (payObj.info.go.t == 4) {
									let lastPage = this.util.getPage()
									setTimeout(() => {
										lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
									}, 3500)
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 3500)
								//console.log('success:' + JSON.stringify(res));
							},
							fail: (err) => {
								this.util.message('取消支付', 2)
								console.log('fail:' + JSON.stringify(err));
								if (payObj.info.cancel) {
									return this.loading = false;
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
							},
							// #endif
							// #ifdef MP-TOUTIAO
							success: (res) => {
								this.util.message('支付成功', 1)
								setTimeout(() => {
									this.util.message('请耐心等待，页面即将跳转', 3, 2000)
								}, 1000)
								if (payObj.info.go.t == 4) {
									let lastPage = this.util.getPage()
									setTimeout(() => {
										lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
									}, 3500)
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 3500)
								//console.log('success:' + JSON.stringify(res));
							},
							fail: (err) => {
								this.util.message('取消支付', 2)
								console.log('fail:' + JSON.stringify(err));
								if (payObj.info.cancel) {
									return this.loading = false;
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
							},
							// #endif
							complete: (e) => {
								console.log("paymentcomplete", e)
							}
						});
						// #endif
						// #ifdef  H5
						chooseWXPay(payres.data).then((res) => {
							if (res == 1) {
								this.util.message('支付成功', 1)
								uni.setStorageSync('payedCoupon', {
									orderId: payObj.orderId,
									paymoney: this.pmoney,
								})
								if (payObj.info.go.t == 4) {
									let lastPage = this.util.getPage()
									lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
									//console.log(lastPage)
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
							} else if (res == 3) {
								this.util.message('取消支付', 2)
								if (payObj.info.cancel) {
									return this.loading = false;
								}
								setTimeout(() => {
									this.go(payObj.info.go)
								}, 1000)
							}
						})
						// #endif
					} else {
						this.util.message('支付成功', 1)
						uni.setStorageSync('payedCoupon', {
							orderId: payObj.orderId,
							paymoney: this.pmoney,
						})
						if (payObj.info.go.t == 4) {
							let lastPage = this.util.getPage()
							lastPage.$vm.paySuccess && lastPage.$vm.paySuccess()
						}
						setTimeout(() => {
							this.go(payObj.info.go)
						}, 1000)
					}
				} else {
					this.loading = false;
				}
				console.log('formSubmit payres', payres)
				//this.util.message(e.detail.value.radiogroup + '支付')
				//this.show = false
			}
		},
		// created() {
		// 	console.log(this.api.platform)
		// },
	}
</script>

<style scoped lang="scss">
	.paytop {
		padding: 30rpx 30rpx 60rpx;
	}

	.paymoeny {
		display: flex;
		align-items: baseline;
	}

	.weui-cell:last-child:after {
		display: block;
	}

	.weui-cell:after {
		left: 112rpx;
	}

	.hdimg {
		width: 52rpx;
		height: 52rpx;
		margin-right: 30rpx;
	}

	.right30::after {
		right: 30rpx;
	}

	.payimg {
		width: 206rpx;
		height: 208rpx;
	}
</style>
